import { useControllableValue, useCreation } from 'ahooks'
import { forwardRef } from 'react'
import Decimal from 'decimal.js'
import LuckyCurrencyInput from '../LuckyCurrencyInput/LuckyCurrencyInput'
import { ENV_MONEY_RATIO } from '@/constant/config'

type CoinValue = number | string | undefined

interface LuckyCoinConvertItemProps {
  /**
   * @description 值
   * @default ''
   */
  value?: CoinValue
  /**
   * @description 默认值
   * @default undefined
   */
  defaultValue?: CoinValue
  /**
   * @description 小数位
   * @default 2
   */
  precision?: number
  /**
   * @description 模式
   * @default write
   */
  mode?: 'read' | 'write'
  /**
   * @description 最大值
   * @default Infinity
   */
  max?: number
  /**
   * @description 最小值
   * @default 0
   */
  min?: number
  onChange?: (value: CoinValue) => void
}

const LuckyCoinConvertField = forwardRef<HTMLDivElement, LuckyCoinConvertItemProps>((props, ref) => {
  const { defaultValue = undefined, precision, mode = 'write', ...restProps } = props

  // 受控/非受控状态
  const [inputValue, setInputValue] = useControllableValue<CoinValue>(props, {
    defaultValue,
  })

  // 是否印尼  env=true是非印尼环境
  const isID = useCreation(() => !window.lucky.env?.env, [])

  // 小数位数
  let coinPrecision = precision
  if (precision === undefined) {
    // 印尼不能输入小数
    coinPrecision = isID ? 0 : 2
  }

  let coinValue = inputValue
  // 非印尼环境 都需要 * / 1000
  if (!isID) {
    coinValue = coinValue === undefined ? undefined : new Decimal(Number(coinValue)).div(ENV_MONEY_RATIO).toString()
  }

  const handleCashChange = (val: CoinValue) => {
    if (!isID) {
      val = val === undefined ? undefined : new Decimal(Number(val)).mul(ENV_MONEY_RATIO).toString()
    }
    setInputValue(val)
  }

  return (
    <LuckyCurrencyInput ref={ref} {...restProps} value={coinValue} mode={mode} precision={coinPrecision} onChange={handleCashChange} />
  )
})

export default LuckyCoinConvertField
